#include <iostream>
#include <cstring>
using namespace  std;
const int N = 510;
int a[N][N];
int dx[] = { 0, 1, 0, -1 };
int dy[] = { 1, 0, -1, 0 };
void solve()
{
    memset(a, 0, sizeof a);
    int n; cin >> n;
    int k = n * n - 1;
    int p = 0;
    int x = 1, y = 1;
    while (k >= 0)
    {
        a[x][y] = k--;
        int nx = x + dx[p], ny = y + dy[p];
        if (nx < 1 || nx > n || ny < 1 || ny > n || a[nx][ny] != 0) p = (p + 1) % 4;
        x = x + dx[p], y = y + dy[p];
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
}

int main()
{
    int t; cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}
